package com.rico.web.websocket;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Aaron
 * @since 2022/3/4
 */
@Service
@Log
public class OkHttpWebSocketListener extends WebSocketListener {



    private static final String URI = "wss://api.zb.com/websocket";

    private static WebSocket CLIENT;

    private static final OkHttpClient OK_CLIENT = new OkHttpClient.Builder()
            .pingInterval(10, TimeUnit.SECONDS)
            .build();

    private static final Request REQUEST = new Request.Builder()
            .url(URI)
            .build();

    public OkHttpWebSocketListener() {
        CLIENT = OK_CLIENT.newWebSocket(REQUEST, this);
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        System.out.println("zb onClosed");
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        log.warning("websocket onClosing, re-connecting");
        CLIENT.close(1000, reason);
        CLIENT = OK_CLIENT.newWebSocket(REQUEST, this);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        log.warning("websocket onFailure, re-connecting");
        CLIENT.close(1001, t.getMessage());
        CLIENT = OK_CLIENT.newWebSocket(REQUEST, this);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        

    }


    @SneakyThrows
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        Message message = new Message();
        webSocket.send(JSON.toJSONString(message));
    }
}
